﻿using BusinessLayer;
using BusinessLayer.DatabaseEntities;
using BusinessLayer.VDataEntities;
using CustomerServiceCenter.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Configuration;
using System.Web;
using System.Web.Security;

namespace CustomerServiceCenter.Auth
{
    public static class AuthenticateService
    {


        static Client client = null;

        public static VPromoter CheckWeiXinUser(long clientID)
        {
            LogHelper.Info("check for wechat ");

            VPromoter promoter = null;

            string userID = string.Empty;

            HttpCookie aCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "userid"];
            HttpCookie client_Cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "clientid"];
            HttpCookie openid_Cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName + "useropenid"];
            long clientid = 0;
            string userOpenid = string.Empty;
            if (client_Cookie != null)
            {
                long.TryParse(FormsAuthentication.Decrypt(client_Cookie.Value).UserData.ToString(), out clientid);
                LogHelper.Info("Validate ClientID，From Cookie :" + clientid);
            }


            if (aCookie == null || client_Cookie == null || clientID != clientid || openid_Cookie == null)
            {
                LogHelper.Info("cookie is null and go to validate ");
                client = ClientBusiness.GetClient(clientID);
                //判断guuid是否存在数据库中
                if (client == null)
                {
                    HttpContext.Current.Response.Redirect("~Error/ErrorURL");
                }
                //LogHelper.Info("数据库判断GUUID,获取到的cropID是："+client.CropID);
                //LogHelper.Info("code" + HttpContext.Current.Request.QueryString["code"]);

                //LogHelper.Info("cookies is null,begin to authenticate");
                //获取token
                WeChatHelper wechatHelp = new WeChatHelper();
                string token = wechatHelp.GetToken(client);
                //获取code的URL
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect", client.CropID, System.Web.HttpUtility.UrlEncode(ConfigurationManager.AppSettings["WeixinBaseUrl"].ToString() + "?id=" + client.Guuid), "snsapi_userinfo", "Test");
                LogHelper.Info("second hand url ：\r\n" + url + "\r\n");
                LogHelper.Info("get token is：\r\n" + token + "\r\n");
                LogHelper.Info("get code is：\r\n" + HttpContext.Current.Request.QueryString["code"] + "\r\n");
                //如果有code
                #region code
                if (HttpContext.Current.Request.QueryString["code"] != null)
                {
                    //获取用户信息
                    String userurl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", client.CropID, client.Secret, HttpContext.Current.Request.QueryString["code"]);
                    LogHelper.Info("third hand url ：\r\n" + userurl + "\r\n");
                    string content = WeChatHelper.SendPost(userurl);
                    var obj = JsonConvert.DeserializeObject(content) as JObject;
                    LogHelper.Info("get user access token info :" + content);
                    LogHelper.Info("get user openid:" + obj["openid"]);
                    if (obj["openid"] == null)
                    {
                        LogHelper.Info("get user openid false: " + content);
                        return promoter;
                    }
                    else
                    {
                        string openid = obj["openid"].ToString();
                        LogHelper.Info("Get UserInfo from wechat:" + obj.ToString());
                        //获取用户信息
                        String requestUrl = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}", token, openid);
                        string userInfo = WeChatHelper.SendPost(requestUrl);
                        var userInfoObj = JsonConvert.DeserializeObject(userInfo) as JObject;
                        LogHelper.Info("get user info:" + userInfoObj);
                        var username = userInfoObj["nickname"] == null ? "name is null" : userInfoObj["nickname"].ToString();
                        VPromoter validatePromoter = PromoterBusiness.ValidatePromoter(username, client.ID, openid);
                        if (validatePromoter == null)
                        {
                            VEndUser enduser = new VEndUser
                            {
                                Name = username,
                                ClientID = client.ID,
                                openid = openid,
                            };
                            PromoterBusiness.AddPromoter(enduser);
                            LogHelper.Info("AddUser:\r\nName:" + enduser.Name + "ClientID:" + enduser.ClientID + "openid:" + enduser.openid);
                        }
                        validatePromoter = PromoterBusiness.ValidatePromoter(username, client.ID, openid);
                        #region 添加Cookie
                        //添加cookie
                        FormsAuthenticationTicket ticket_user = new FormsAuthenticationTicket(1, FormsAuthentication.FormsCookieName + "userid", DateTime.Now,
                            DateTime.Now.AddMinutes(5), true, username);
                        FormsAuthenticationTicket ticket_openid = new FormsAuthenticationTicket(1, FormsAuthentication.FormsCookieName + "useropenid", DateTime.Now,
                            DateTime.Now.AddMinutes(5), true, openid);
                        string userinfoticket = FormsAuthentication.Encrypt(ticket_user);
                        string useropenidticket = FormsAuthentication.Encrypt(ticket_openid);
                        //添加userid,openid到cookie
                        var cookie_user = new HttpCookie(FormsAuthentication.FormsCookieName + "userid", userinfoticket);
                        cookie_user.HttpOnly = true;
                        cookie_user.Expires = DateTime.Now.AddHours(20);
                        HttpContext.Current.Response.Cookies.Add(cookie_user);

                        var cookie_useropenid = new HttpCookie(FormsAuthentication.FormsCookieName + "useropenid", useropenidticket);
                        cookie_useropenid.HttpOnly = true;
                        cookie_useropenid.Expires = DateTime.Now.AddHours(20);
                        HttpContext.Current.Response.Cookies.Add(cookie_useropenid);

                        //添加cookie
                        FormsAuthenticationTicket ticket_client = new FormsAuthenticationTicket(1, FormsAuthentication.FormsCookieName + "clientid", DateTime.Now,
                            DateTime.Now.AddMinutes(5), true, client.ID.ToString());
                        string clientinfoticket = FormsAuthentication.Encrypt(ticket_client);
                        //添加clientid到cookie
                        var cookie_client = new HttpCookie(FormsAuthentication.FormsCookieName + "clientid", clientinfoticket);
                        cookie_client.HttpOnly = true;
                        cookie_client.Expires = DateTime.Now.AddHours(20);
                        HttpContext.Current.Response.Cookies.Add(cookie_client);
                        #endregion 添加Cookie结束
                        //userID = obj["UserId"].ToString();
                        promoter = validatePromoter;
                    }
                }

                else
                {
                    HttpContext.Current.Response.Redirect(url);
                }
                #endregion
            }

            else
            {

                if (aCookie != null && !string.IsNullOrEmpty(aCookie.Value) && client_Cookie != null && !string.IsNullOrEmpty(client_Cookie.Value) && openid_Cookie != null && !string.IsNullOrEmpty(client_Cookie.Value))
                {
                    try
                    {
                        FormsAuthenticationTicket tit = FormsAuthentication.Decrypt(aCookie.Value);
                        FormsAuthenticationTicket tit_client = FormsAuthentication.Decrypt(client_Cookie.Value);
                        FormsAuthenticationTicket tit_openid = FormsAuthentication.Decrypt(openid_Cookie.Value);
                        userID = tit.UserData;
                        userOpenid = string.IsNullOrEmpty(tit_openid.UserData) ? "" : tit_openid.UserData.ToString();
                        long.TryParse(tit_client.UserData.ToString(), out clientid);
                        promoter = new VPromoter
                        {
                            ChineseName = userID,
                            ClientID = clientid,
                            openid = userOpenid
                        };
                        LogHelper.Info("Get User from cookie:" + promoter.ToString());
                    }
                    catch
                    {
                        userID = string.Empty;
                    }
                }
                return promoter;
            }
            return promoter;
        }
    }
}